/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.actionControll {
	import com.googlecode.milib.base.MLActionClass;
	import com.googlecode.milib.base.MLBaseClass;
	import com.googlecode.milib.vo.MLEvent;

	/**
	 * @author Marek Brun
	 */
	public class OneActionRunningController extends MLBaseClass {

		private var actions:Array=[];
		private var actionToStart:MLActionClass;

		public function OneActionRunningController(actions:Array) {
			
			var i:uint;
			var loop:MLActionClass;
			for(i=0;i<actions.length;i++){
				loop=actions[i];
				addAction(loop);
			}
		}
		
		public function addAction(loop:MLActionClass):void {
			actions.push(loop);
		}
		
		public function startAction(action:MLActionClass):void {
			if(action==null){
				throw new Error('Passed action can\'t be null');
			}
			actionToStart=action;
			tryStartCurrentActionToStart();
		}
		
		private function tryStartCurrentActionToStart():void {
			if(!actionToStart){ return; }
			if(actionToStart.getIsRunning()){
				actionToStart=null;
				return;
			}
			var i:uint;
			var loop:MLActionClass, actionToFinish:MLActionClass;
			for(i=0;i<actions.length;i++){
				loop=actions[i];
				if(loop!= actionToStart) {
					if(loop.getIsRunning()){
						actionToFinish=loop;
						break;
					}
				}
			}
			if(actionToFinish){
				loop.addEventListener(loop.event_ActionFinish, onActionToFinishFinish);
				loop.finish();
			}else{
				actionToStart.start();
				actionToStart=null;
			}
		}
		
//********************************************************************************************
//		events for OneActionRunning
//********************************************************************************************
		protected function onActionToFinishFinish(event:MLEvent):void {
			event.info.hero.removeEventListener(event.info.hero.event_ActionFinish, onActionToFinishFinish);
			tryStartCurrentActionToStart();
		}
		
	}
}
